﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VIFON.BLL;
using VIFON.DAL;
namespace VIFON
{
    public partial class frmCustomerSummary : Telerik.WinControls.UI.RadForm
    {
        BLRegion blRegion = new BLRegion();
        BLCustomer blCustomer = new BLCustomer();
        VIFON.DAL.Region re = new VIFON.DAL.Region();
        public frmCustomerSummary()
        {
            InitializeComponent();
        } 
        public void SetCustomerFormatDTP()
        {
            dtpFrom.Format = DateTimePickerFormat.Custom;
            dtpFrom.CustomFormat = "MM/yyyy";
            dtpFrom.ShowUpDown = true;
            dtpTo.Format = DateTimePickerFormat.Custom;
            dtpTo.CustomFormat = "MM/yyyy";
            dtpTo.ShowUpDown = true;

            DateTimePickerFrom.Format = DateTimePickerFormat.Custom;
            DateTimePickerFrom.CustomFormat = "MM/yyyy";
            DateTimePickerFrom.ShowUpDown = true;
            DateTimePickerTo.Format = DateTimePickerFormat.Custom;
            DateTimePickerTo.CustomFormat = "MM/yyyy";
            DateTimePickerTo.ShowUpDown = true;

            dtpfrom2.Format = DateTimePickerFormat.Custom;
            dtpfrom2.CustomFormat = "MM/yyyy";
            dtpfrom2.ShowUpDown = true;
            dtpto2.Format = DateTimePickerFormat.Custom;
            dtpto2.CustomFormat = "MM/yyyy";
            dtpto2.ShowUpDown = true;


        }
        private void LoadRegions()
        {
            ddlRegion.DisplayMember = "Name";
            ddlRegion.ValueMember = "Id";
            ddlRegion.DataSource = BLRegion.GetRegions();
        }
        private void CustomerSummary_Load(object sender, EventArgs e)
        {
            SetCustomerFormatDTP();                      
            LoadRegions();
        }
        //Area Tab 1
        private void ShowCustomerSummaryByCondition()
        {
             try
            {
                using (var db = new DBVIFONDataContext())
                {
                    var result = from Customers in db.Customers
                                 from Products in db.Products
                                 from BillDetails in db.BillDetails
                                 from Bills in db.Bills
                                 where
                                   Customers.Id == Bills.CustomerId 
                                   && Products.Id == BillDetails.ProductId
                                   &&Bills.Id == BillDetails.BillId 
                                   &&Customers.Region == int.Parse(ddlRegion.SelectedValue.ToString())
                                   && Bills.CreatedDate.Month >= dtpFrom.Value.Date.Month
                                   && Bills.CreatedDate.Month <= dtpTo.Value.Date.Month
                                   && Bills.CreatedDate.Year >= dtpFrom.Value.Date.Year
                                   && Bills.CreatedDate.Year <= dtpTo.Value.Date.Year
                                 group new { Customers, Products, BillDetails } by new
                                 {
                                     Customers.Id,
                                     Customers.CustomerName,
                                     Customers.Address
                                 } into g
                                 select new
                                 {
                                     CustomerId = g.Key.Id,
                                     CustomerName = g.Key.CustomerName,
                                     CustomerAddress = g.Key.Address,
                                     ThanhTien = (double?)g.Sum(p => ((double)p.Products.Prices - ((double)p.Products.Prices * p.Customers.Discount / 100)) * (double)p.BillDetails.Amounts),
                                     TongSoLuong = (int?)g.Sum(p => p.BillDetails.Amounts)
                                 };
                    if (result != null)
                    {

                        gvshow.Rows.Clear();
                        foreach (var l in result)
                        {
                            gvshow.Rows.Add(l.CustomerId, l.CustomerAddress, l.CustomerName, l.TongSoLuong, l.ThanhTien, ddlRegion.Text);
                        }
                    }          

                }  
            }
            catch{throw;}
        }
        private void ShowCustomerSummary()
        {
            try
            {
                using (var db = new DBVIFONDataContext())
                {
                    var result = from Customers in db.Customers
                                 from Products in db.Products
                                 from BillDetails in db.BillDetails
                                 from Bills in db.Bills
                                 where
                                   Customers.Id == Bills.CustomerId
                                   && Products.Id == BillDetails.ProductId
                                   && Bills.Id == BillDetails.BillId
                                   && Bills.CreatedDate.Month >= dtpFrom.Value.Date.Month
                                   && Bills.CreatedDate.Month <= dtpTo.Value.Date.Month
                                   && Bills.CreatedDate.Year >= dtpFrom.Value.Date.Year
                                   && Bills.CreatedDate.Year <= dtpTo.Value.Date.Year
                                 group new { Customers, Products, BillDetails } by new
                                 {
                                     Customers.Id,
                                     Customers.CustomerName,
                                     Customers.Address,
                                     Customers.Region
                                 } into g
                                 select new
                                 {
                                    CustomerId=g.Key.Id,
                                    CustomerName=g.Key.CustomerName,
                                    CustomerAddress=g.Key.Address,
                                    RegionId=g.Key.Region,
                                    ThanhTien = (double?)g.Sum(p => ((double)p.Products.Prices - ((double)p.Products.Prices * p.Customers.Discount / 100)) * (double)p.BillDetails.Amounts),
                                    TongSoLuong = (int?)g.Sum(p => p.BillDetails.Amounts)
                                 };
                    if (result != null)
                    {

                        gvshow.Rows.Clear();
                        foreach (var l in result)
                        {
                            re = blRegion.GetRegionNameById(int.Parse(l.RegionId.ToString())); 
                            gvshow.Rows.Add(l.CustomerId, l.CustomerAddress, l.CustomerName, l.TongSoLuong, l.ThanhTien, re.Name);
                        }
                    }
                    gvshow.Refresh();
                }
            }
            catch { throw; }
        }
        private void btnxem_Click(object sender, EventArgs e)
        {
            //ShowCustomerSummary();
            DateTime timefrom = DateTime.Parse(dtpFrom.Text);
            DateTime timeto = DateTime.Parse(dtpTo.Text);
            if(timefrom>timeto)
            {
                MessageBox.Show("Ngày chọn sai. Vui lòng xem lại");
            }
            else
            {
                ShowCustomerSummaryByCondition();
            }            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            DateTime timefrom = DateTime.Parse(dtpFrom.Text);
            DateTime timeto = DateTime.Parse(dtpTo.Text);
            if (timefrom > timeto)
            {
                MessageBox.Show("Ngày chọn sai. Vui lòng xem lại");
            }
            else
            {
                ShowCustomerSummary();
            }         
        }

        private void button2_Click(object sender, EventArgs e)
        {
            List<ReportCustomerByRegion> reportlist = new List<ReportCustomerByRegion>();
            for (int i = 0; i < gvshow.Rows.Count; i++)
            {
                ReportCustomerByRegion report = new ReportCustomerByRegion();
                report.CustomerName = gvshow.Rows[i].Cells["colCustomerName"].Value.ToString();
                report.DateTime = dtpFrom.Text;
                report.Address = gvshow.Rows[i].Cells["colAddress"].Value.ToString().Substring(gvshow.Rows[i].Cells["colAddress"].Value.ToString().LastIndexOf(",")).Replace(",", "");
                report.TotalMoney = double.Parse(gvshow.Rows[i].Cells["colTotal"].Value.ToString());
                report.TotalWeight = int.Parse(gvshow.Rows[i].Cells["colTotalWeight"].Value.ToString());
                report.RegionName = gvshow.Rows[i].Cells["colRegionName"].Value.ToString();
                report.Temp2 = dtpTo.Text;
                reportlist.Add(report);
            }
            frmReportByRegion frm = new frmReportByRegion(reportlist);
            frm.Show();
        }
        //Area Tab2
        private void GetListCustomerInRegion()
        {
            try
            {
                using (var db = new DBVIFONDataContext())
                {
                    var sql = from Bills in db.Bills
                              from Customers in db.Customers
                              from BillDetails in db.BillDetails
                              from Products in db.Products
                              where
                                Bills.Id == BillDetails.BillId &&
                                Customers.Id == Bills.CustomerId &&
                                Products.Id == BillDetails.ProductId
                                && Bills.CreatedDate.Month >= DateTimePickerFrom.Value.Date.Month
                                && Bills.CreatedDate.Month <= DateTimePickerTo.Value.Date.Month
                                && Bills.CreatedDate.Year >= DateTimePickerFrom.Value.Date.Year
                                && Bills.CreatedDate.Year <= DateTimePickerTo.Value.Date.Year
                              group new { Customers, Products, BillDetails } by new
                              {
                                  Customers.Id,
                                  Customers.CustomerName,
                                  Customers.Address,
                                  Customers.Region,
                                  ProductId = Products.Id,
                                  DiscountPrice = (double?)((double)Products.Prices - ((double)Products.Prices * Customers.Discount / 100))
                              } into g
                              select new
                              {
                                  customerID = g.Key.Id,
                                  customerName = g.Key.CustomerName,
                                  customerAddress = g.Key.Address,
                                  productId = g.Key.ProductId,
                                  RegionId = g.Key.Region,
                                  DiscountPrice = g.Key.DiscountPrice,
                                  TongSoLuong = (int?)g.Sum(p => p.BillDetails.Amounts),
                                  ThanhTien = (double?)g.Sum(p => ((double)p.Products.Prices - ((double)p.Products.Prices * p.Customers.Discount / 100)) * (double)p.BillDetails.Amounts)
                              };
                    if(sql!=null)
                    {
                        gvView.Rows.Clear();                                               
                        foreach(var item in sql)
                        {
                            re = blRegion.GetRegionNameById(int.Parse(item.RegionId.ToString()));                            
                            gvView.Rows.Add(item.customerID,item.customerName,item.customerAddress,item.productId,item.DiscountPrice,item.TongSoLuong,item.ThanhTien,re.Name);
                        }
                    }
                }
            }   
            catch { throw; }
           
        }
        private void btnview_Click(object sender, EventArgs e)
        {
            
            DateTime timefrom = DateTime.Parse(DateTimePickerFrom.Text);
            DateTime timeto = DateTime.Parse(DateTimePickerTo.Text);
            if (timefrom > timeto)
            {
                MessageBox.Show("Ngày chọn sai. Vui lòng xem lại");
            }
            else
            {
                GetListCustomerInRegion();
            }            
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            List<CustomerByRegionDetail> reportlist = new List<CustomerByRegionDetail>();
            for(int i = 0;i<gvView.Rows.Count;i++)
            {
                //string address = gvView.Rows[i].Cells["colAddress"].Value.ToString();
                //address = address.Substring(address.LastIndexOf(",")).Replace(",", "");
                CustomerByRegionDetail report = new CustomerByRegionDetail();
                report.CustomerID = int.Parse(gvView.Rows[i].Cells["colCustomerId"].Value.ToString());
                report.CustomerName = gvView.Rows[i].Cells["colCustomerName"].Value.ToString();
                report.Address = gvView.Rows[i].Cells["colAddress"].Value.ToString().Substring(gvView.Rows[i].Cells["colAddress"].Value.ToString().LastIndexOf(",")).Replace(",","");
                report.DateTimeFrom = DateTimePickerFrom.Text;
                report.DateTimeTo = DateTimePickerTo.Text;
                report.RegionName = gvView.Rows[i].Cells["colRegionName"].Value.ToString();
                report.DiscountPrice=double.Parse(gvView.Rows[i].Cells["colDiscountPrice"].Value.ToString());
                report.TotalWeight = int.Parse(gvView.Rows[i].Cells["colTotalQty"].Value.ToString());
                report.TotalMoney = double.Parse(gvView.Rows[i].Cells["colTotalMoney"].Value.ToString());
                report.Temp2 = gvView.Rows[i].Cells["colProductId"].Value.ToString();
                reportlist.Add(report);
            }
            frmReportCustomerDetail frm = new frmReportCustomerDetail(reportlist);
            frm.Show();
        }
        // Tab 3
        private void ShowProductList()
        {
            using (var db = new DBVIFONDataContext())
            {
                var sql = from Products in db.Products
                          from Bills in db.Bills
                          from BillDetails in db.BillDetails
                          where
                            Products.Id == BillDetails.ProductId 
                            && Bills.Id == BillDetails.BillId
                            && Bills.CreatedDate.Month >= dtpfrom2.Value.Date.Month
                            && Bills.CreatedDate.Month <= dtpto2.Value.Date.Month
                            && Bills.CreatedDate.Year >= dtpfrom2.Value.Date.Year
                            && Bills.CreatedDate.Year <= dtpto2.Value.Date.Year
                          group new { Products, BillDetails } by new
                          {
                              Products.Id,
                              Products.ProductName
                          } into g
                          select new
                          {
                              ProductId = g.Key.Id,
                              ProductName = g.Key.ProductName,
                              TotalWeight = (int?)g.Sum(p => p.BillDetails.Amounts),
                              TotalMoney = (int?)g.Sum(p => p.Products.Prices * p.BillDetails.Amounts)
                          };
                if(sql!=null)
                {
                    gvViewProduct.Rows.Clear();
                    foreach(var item in sql)
                    {
                        string temp = "";
                        temp = item.ProductName.ToString().ToLower();
                        if(temp.Contains("gà"))
                        {
                            gvViewProduct.Rows.Add(item.ProductId, item.ProductName, item.TotalWeight, item.TotalMoney, "Gà");
                        }
                        else if(temp.Contains("vịt"))
                        {
                            gvViewProduct.Rows.Add(item.ProductId, item.ProductName, item.TotalWeight, item.TotalMoney, "Vịt");
                        }
                        else if (temp.Contains("heo"))
                        {
                            gvViewProduct.Rows.Add(item.ProductId, item.ProductName, item.TotalWeight, item.TotalMoney, "Heo");
                        }
                        else if (temp.Contains("bò"))
                        {
                            gvViewProduct.Rows.Add(item.ProductId, item.ProductName, item.TotalWeight, item.TotalMoney, "Bò");
                        }
                        else if (temp.Contains("trâu"))
                        {
                            gvViewProduct.Rows.Add(item.ProductId, item.ProductName, item.TotalWeight, item.TotalMoney, "Trâu");
                        }
                        else
                        {
                            gvViewProduct.Rows.Add(item.ProductId, item.ProductName, item.TotalWeight, item.TotalMoney, "Khác");
                        }                        
                    }
                    gvViewProduct.Refresh();
                }
            }
            
        }
        private void btnViewProduct_Click(object sender, EventArgs e)
        {
            DateTime timefrom = DateTime.Parse(dtpfrom2.Text);
            DateTime timeto = DateTime.Parse(dtpto2.Text);
            if (timefrom > timeto)
            {
                MessageBox.Show("Ngày chọn sai. Vui lòng xem lại");
            }
            else
            {
                ShowProductList();
            }   
           
        }

        private void btnPrintProduct_Click(object sender, EventArgs e)
        {
            List<ReportByProduct> reportlist = new List<ReportByProduct>();
            for(int i=0;i<gvViewProduct.Rows.Count;i++)
            {
                ReportByProduct report = new ReportByProduct();
                report.ProductId = gvViewProduct.Rows[i].Cells["colProductId"].Value.ToString();
                report.ProductName = gvViewProduct.Rows[i].Cells["colProductName"].Value.ToString();
                report.ProductType = gvViewProduct.Rows[i].Cells["colProductType"].Value.ToString();
                report.TotalWeight = int.Parse(gvViewProduct.Rows[i].Cells["colTotalWeight"].Value.ToString());
                report.TotalMoney = int.Parse(gvViewProduct.Rows[i].Cells["colTotalMoney"].Value.ToString());
                report.DatetimeFrom = dtpfrom2.Text;
                report.DatetimeTo = dtpto2.Text;
                reportlist.Add(report);
            }
            frmReportByCustomer frm = new frmReportByCustomer(reportlist);
            frm.Show();
        }        
    }
}
